package edu.berkeley.cs160.GroupC;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class Menu extends WorkoutMusicActivity {

	private ImageButton editPlaylistButton;
	private ImageButton calibrateButton;
	private ImageButton startRunningButton;
	
    /** Called when the activity is first created. */
    @Override   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }
    
    public void init() {
    	editPlaylistButton = (ImageButton) findViewById(R.id.EditPlaylistButton);
    	calibrateButton = (ImageButton) findViewById(R.id.CalibrateButton);
    	startRunningButton = (ImageButton) findViewById(R.id.StartButton);
    	
    	editPlaylistButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Menu.this, AddSongActivity.class);
				startActivity(intent);
			}
		});
    	calibrateButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				calibrateInstructions();
				
			}
		});
    	startRunningButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				WorkoutMusicApplication app = (WorkoutMusicApplication) getApplication();
				
				Log.v("SUS", "Clicked on startRunning.");
				
				if (!app.getCurrentPlaylist().isEmpty()) {
					Log.v("SUS", "Playlist has "+app.getCurrentPlaylist().size()+" songs.");
					Intent intent = new Intent(Menu.this, PlaySongs.class);
					startActivity(intent);
				}
				else {
					Toast.makeText(Menu.this, "No songs found!", Toast.LENGTH_SHORT).show();
					return;
				}
			}
		});
    }
    
    private static int calibrateInstructionState = 0;
    
    public void calibrateInstructions() {
    	
    	Dialog dialog = new Dialog(this);
    	dialog.setTitle("App Calibration");
    	dialog.setContentView(R.layout.calibrate);
    	
    	calibrateInstructionState = 0;
    	
    	Button backButton = (Button) dialog.findViewById(R.id.calibrateBackButton);
    	Button nextButton = (Button) dialog.findViewById(R.id.calibrateNextButton);
    	
    	backButton.setOnClickListener(new CalibrateBackListener(dialog));
    	nextButton.setOnClickListener(new CalibrateNextListener(dialog));
    	
    	dialog.show();
    	
    }
    
    private class CalibrateBackListener implements OnClickListener {
    	
    	Dialog dialog;
    	
    	public CalibrateBackListener(Dialog d) {
    		this.dialog = d;
    	}

		public void onClick(View v) {
			switch (calibrateInstructionState) {
			case 0:
				dialog.dismiss();
				break;
			case 1:
				TextView text = (TextView) dialog.findViewById(R.id.instructionsText);
				text.setText(R.string.instructions1);
				calibrateInstructionState--;
				break;
			default:
				break;
			}
		}
    	
    }
    
    private class CalibrateNextListener implements OnClickListener {
    	
    	Dialog dialog;
    	
    	public CalibrateNextListener(Dialog d) {
    		this.dialog = d;
    	}
    	
    	public void onClick(View v) {
    		switch (calibrateInstructionState) {
    		case 0:
    			TextView text = (TextView) dialog.findViewById(R.id.instructionsText);
    			text.setText(R.string.instructions2);
    			calibrateInstructionState++;
    			break;
    		case 1:
    			dialog.dismiss();
    			calibrate();
    		default:
    			break;
    		}
    	}
    	
    }
    
    private static int calibrationState = 0;
    private ProgressDialog currentCalibrationDialog = null;
    private ProgressThread progressThread;
    private Context calibrationContext;
    private MediaPlayer mp;
    
    public void calibrate() {
    	
    	AlertDialog.Builder builder;
    	AlertDialog alert;
    	calibrationContext = this;
    	
    	mp = MediaPlayer.create(this, R.raw.secret);
    	
    	switch (calibrationState) {
    	case 0:
    		
    		builder = new AlertDialog.Builder(this);
    		builder.setMessage(R.string.calibrateLow);
    		builder.setCancelable(true);
    		builder.setPositiveButton(R.string.calibrateStart, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				
    				ProgressDialog progressDialog;
    				progressDialog = new ProgressDialog(calibrationContext);
    				progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    				progressDialog.setMessage("Calibrating SLOW JOG... Think slow thoughts...");
    				progressDialog.setCancelable(false);
    				progressDialog.setProgress(0);
    				
    				currentCalibrationDialog = progressDialog;
    				
    				progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
						public void onDismiss(DialogInterface dialog) {
							calibrationState++;
							calibrate();
						}
    				});

    				progressDialog.show();
    				
    				progressThread = new ProgressThread(handler, 0);
    				progressThread.start();
    				
    			}
    		});
    		builder.setNegativeButton(R.string.calibrateCancel, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				calibrationState = 0;
    				dialog.cancel();
    			}
    		});

    		alert = builder.create();
    		alert.show();
    		
    		break;
    	case 1:
    		
    		builder = new AlertDialog.Builder(this);
    		builder.setMessage(R.string.calibrateMedium);
    		builder.setCancelable(true);
    		builder.setPositiveButton(R.string.calibrateStart, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				
    				ProgressDialog progressDialog;
    				progressDialog = new ProgressDialog(calibrationContext);
    				progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    				progressDialog.setMessage("Calibrating JOG... Move at a brisk pace.");
    				progressDialog.setCancelable(false);
    				progressDialog.setProgress(0);
    				
    				currentCalibrationDialog = progressDialog;
    				
    				progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
						public void onDismiss(DialogInterface dialog) {
							calibrationState++;
							calibrate();
						}
    				});

    				Log.v("CAL", "Showing dialog...");
    				progressDialog.show();
    				
    				Log.v("CAL", "Starting progress thread...");
    				progressThread = new ProgressThread(handler, 1);
    				progressThread.start();
    				Log.v("CAL", "Done.");
    				
    			}
    		});
    		builder.setNegativeButton(R.string.calibrateCancel, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				calibrationState = 0;
    				dialog.cancel();
    			}
    		});
    		
    		alert = builder.create();
    		alert.show();
    		
    		break;
    	case 2:
    		
    		builder = new AlertDialog.Builder(this);
    		builder.setMessage(R.string.calibrateHigh);
    		builder.setCancelable(true);
    		builder.setPositiveButton(R.string.calibrateStart, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				
    				ProgressDialog progressDialog;
    				progressDialog = new ProgressDialog(calibrationContext);
    				progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    				progressDialog.setMessage("Calibrating SPRINT... RUN LIKE THE WIND!");
    				progressDialog.setCancelable(false);
    				progressDialog.setProgress(0);
    				
    				currentCalibrationDialog = progressDialog;
    				
    				progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
						public void onDismiss(DialogInterface dialog) {
							calibrationState++;
							calibrate();
						}
    				});

    				progressDialog.show();
    				
    				progressThread = new ProgressThread(handler, 2);
    				progressThread.start();
    				
    			}
    		});
    		builder.setNegativeButton(R.string.calibrateCancel, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				calibrationState = 0;
    				dialog.cancel();
    			}
    		});
    		
    		alert = builder.create();
    		alert.show();
    		break;
    	case 3:
    		calibrationState = 0;
    		
    		builder = new AlertDialog.Builder(this);
    		builder.setTitle("Calibration Complete");
    		builder.setMessage("Congratulations! You can now use your app to your heart's content!");
    		builder.setCancelable(true);
    		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				dialog.dismiss();
    			}
    		});
    		
    		alert = builder.create();
    		alert.show();
    		
    		break;
    	default:
    		break;
    	}
    	
    }
    
 // Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int total = msg.arg1;
            currentCalibrationDialog.setProgress(total);
            if (total > 100){
            	progressThread.setState(ProgressThread.STATE_DONE);
            	try {
	            	mp.start();
            	}
            	catch (Exception e) {
            	}
                currentCalibrationDialog.dismiss();
                
                switch (msg.arg2) {
                case 0:
                	Toast.makeText(calibrationContext, "SLOW JOG calibration complete!", Toast.LENGTH_SHORT).show();
                	break;
                case 1:
                	Toast.makeText(calibrationContext, "REGULAR JOG calibration complete! Your pace was 152 Steps/Minute", Toast.LENGTH_LONG).show();
                	break;
                case 2:
                	Toast.makeText(calibrationContext, "SPRINT calibration complete!", Toast.LENGTH_LONG).show();
                	break;
                default:
                	break;
                }
            }
        }
    };

    /** Nested class that performs progress calculations (counting) */
    private class ProgressThread extends Thread {
        Handler mHandler;
        final static int STATE_DONE = 0;
        final static int STATE_RUNNING = 1;
        int mState;
        int total;
        int type;
       
        ProgressThread(Handler h, int t) {
            mHandler = h;
            type = t;
        }
       
        public void run() {
            mState = STATE_RUNNING;   
            total = 0;
            while (mState == STATE_RUNNING) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Log.e("ERROR", "Thread Interrupted");
                }
                Message msg = mHandler.obtainMessage();
                msg.arg1 = total;
                msg.arg2 = type;
                mHandler.sendMessage(msg);
                total++;
            }
        }
        
        /* sets the current state for the thread,
         * used to stop the thread */
        public void setState(int state) {
            mState = state;
        }
    }
    
}